import { loginReq, getUserInfo } from "@/service/user";
import { defineStore } from "pinia";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import { showToast, showFailToast, showConfirmDialog } from "vant";
const getDefaultState = () => {
  return {
    token: getToken(), //刷新页面时，会从本地拿取token
    userInfo: {},
  };
};
export const useUser = defineStore("useStore", {
  state: getDefaultState,
  actions: {
    // 登录
    login(userInfo) {
      const { userName, passWord } = userInfo;
      return new Promise((resolve, reject) => {
        loginReq({ username: userName.trim(), password: passWord })
          .then(async (response) => {
            if (response.code == 0) {
              const { data } = response;
              this.token = data.token;
              setToken(data.token);
              // 将用户信息赋值
              await this.getInfo()
              showToast("登录成功！");
            } else {
              showFailToast(response.msg);
              reject('error')
            }
            resolve('success');
          })
          .catch((error) => {
            // showFailToast("系统错误！");
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res) => {
            this.userInfo = res.data
            resolve(res.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出
    logout() {
      return new Promise((resolve, reject) => {
        removeToken(); // must remove  token  first
        resetRouter();
        resolve();
      });
    },
    // 清除token
    resetToken() {
      return new Promise((resolve) => {
        removeToken(); // must remove  token  first
        this.$reset();
        resolve();
      });
    },
  },
});
